from fastapi import APIRouter, HTTPException,UploadFile, File, Form
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi import APIRouter, File, UploadFile, Form, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.requests import Request

from app.utils.deepseekimg_client import  DeepSeekImgClient
from app.utils.deepseek_client import DeepSeekClient
from app.main import templates
import logging
from pydantic import BaseModel
from fastapi.templating import Jinja2Templates
import PyPDF2
import io
import os
from server.utils.doc_generator import DocGenerator
from pdf2image import convert_from_bytes
import pytesseract
from PIL import Image

from fastapi import File, UploadFile
import base64

router = APIRouter()
deepseek_client = DeepSeekClient()
deepseekImg_client = DeepSeekImgClient()
templates = Jinja2Templates(directory="templates")

logger = logging.getLogger(__name__)


# 定义请求体模型
class ChatRequest(BaseModel):
    message: str


@router.get("/", response_class=HTMLResponse)
async def root(request: Request):
    return templates.TemplateResponse(
        "index.html",
        {"request": request}
    )


@router.post("/api/chat")
async def chat(request: ChatRequest):
    try:
        logger.info(f"收到用户消息: {request.message}")
        response = await deepseek_client.send_message(request.message)
        logger.info(f"API 响应: {response}")
        return {"response": response.get("choices", [{}])[0].get("message", {}).get("content", "")}
    except Exception as e:
        logger.error(f"发生错误: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/wildlife", response_class=HTMLResponse)
async def wildlife(request: Request):
    return templates.TemplateResponse(
        "wildlife.html",
        {"request": request}
    )


@router.get("/pdf-extract", response_class=HTMLResponse)
async def wildlife(request: Request):
    return templates.TemplateResponse(
        "pdf_extract.html",
        {"request": request}
    ) 

@router.post("/api/chat-stream")
async def chat_stream(file: UploadFile = File(...), prompt: str = Form(...)):
    try:
        # 读取图片文件
        image_content = await file.read()
        image_base64 = base64.b64encode(image_content).decode('utf-8')


        # 获取流式生成器
        stream_generator = deepseekImg_client.chat_with_image_stream(
            image_base64=image_base64,
            prompt=prompt
        )

        # 返回流式响应
        return await deepseekImg_client.process_stream_response(stream_generator)

    except Exception as e:
        logger.error(f"流式对话请求失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/download-word/{filename}")
async def download_word(filename: str):
    try:
        # 设置文档存储路径
        doc_path = os.path.join("temp", "docs")
        file_path = os.path.join(doc_path, filename)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail="文件不存在")
        
        # 返回文件
        return FileResponse(
            file_path,
            media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            filename=filename
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/api/extract-pdf")
async def extract_pdf(pdf: UploadFile = File(...)):
    try:
        # 读取上传的PDF文件
        pdf_content = await pdf.read()
        pdf_file = io.BytesIO(pdf_content)
        
        # 提取文本内容
        pdf_reader = PyPDF2.PdfReader(pdf_file)
        text_content = ""
        
        # 将PDF转换为图片
        images = convert_from_bytes(pdf_content,poppler_path=r'D:\Develop\poppler-24.08.0\Library\bin')
        image_texts = []
        
        # 处理每一页
        for i, page in enumerate(pdf_reader.pages):
            # 提取文本
            page_text = page.extract_text()
            text_content += page_text + "\n"
            
            # 对当前页面的图片进行OCR
            if i < len(images):  # 确保有对应的图片
                image = images[i]
                # 进行OCR识别
                image_text = pytesseract.image_to_string(image, lang='chi_sim+eng')
                if image_text.strip():  # 如果识别出文字
                    image_texts.append(f"第{i+1}页图片文字：\n{image_text}\n")
        
        # 合并所有文本
        combined_text = text_content
        if image_texts:
            combined_text += "\n=== 图片中识别的文字 ===\n"
            combined_text += "\n".join(image_texts)
            
        if not combined_text.strip():
            return JSONResponse(
                status_code=400,
                content={"success": False, "error": "无法从PDF中提取文本"}
            )
        # 调用AI处理文本
        logger.info("text_content:"+text_content)
        logger.info("combined_text"+combined_text)
        deepseek_client = DeepSeekClient()
        prompt = f"""请分析以下文本内容（包括从图片中识别的文字），提供重要信息的总结：

{combined_text}

请提供：
1. 文档主要内容概述
2. 关键信息点提取
3. 重要结论（如果有）
4. 图片文字内容的相关性分析（如果有）
"""
        ai_response = await deepseek_client.send_message(prompt)
        ai_result = ai_response['choices'][0]['message']['content']
        
        # 生成Word文档
        doc_generator = DocGenerator()
        doc_path = os.path.join("temp", "docs")
        filename = doc_generator.generate_doc(
            original_text=combined_text,
            ai_analysis=ai_result,
            output_path=doc_path
        )
        
        return JSONResponse(content={
            "success": True,
            "original_text": combined_text,
            "ai_result": ai_result,
            "filename": filename
        })
        
    except Exception as e:
        logger.error(f"PDF处理错误: {str(e)}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={"success": False, "error": str(e)})

@router.get("/download-word/{filename}")
async def download_word(filename: str):
    try:
        # 设置文档存储路径
        doc_path = os.path.join("temp", "docs")
        file_path = os.path.join(doc_path, filename)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail="文件不存在")
        
        # 返回文件
        return FileResponse(
            file_path,
            media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            filename=filename
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/api/extract-pdf")
async def extract_pdf(pdf: UploadFile = File(...)):
    try:
        # 读取上传的PDF文件
        pdf_content = await pdf.read()
        pdf_file = io.BytesIO(pdf_content)
        
        # 提取文本内容
        pdf_reader = PyPDF2.PdfReader(pdf_file)
        text_content = ""
        
        # 将PDF转换为图片
        images = convert_from_bytes(pdf_content,poppler_path=r'D:\Develop\poppler-24.08.0\Library\bin')
        image_texts = []
        
        # 处理每一页
        for i, page in enumerate(pdf_reader.pages):
            # 提取文本
            page_text = page.extract_text()
            text_content += page_text + "\n"
            
            # 对当前页面的图片进行OCR
            if i < len(images):  # 确保有对应的图片
                image = images[i]
                # 进行OCR识别
                image_text = pytesseract.image_to_string(image, lang='chi_sim+eng')
                if image_text.strip():  # 如果识别出文字
                    image_texts.append(f"第{i+1}页图片文字：\n{image_text}\n")
        
        # 合并所有文本
        combined_text = text_content
        if image_texts:
            combined_text += "\n=== 图片中识别的文字 ===\n"
            combined_text += "\n".join(image_texts)
            
        if not combined_text.strip():
            return JSONResponse(
                status_code=400,
                content={"success": False, "error": "无法从PDF中提取文本"}
            )
        # 调用AI处理文本
        logger.info("text_content:"+text_content)
        logger.info("combined_text"+combined_text)
        deepseek_client = DeepSeekClient()
        prompt = f"""请分析以下文本内容（包括从图片中识别的文字），提供重要信息的总结：

{combined_text}

请提供：
1. 文档主要内容概述
2. 关键信息点提取
3. 重要结论（如果有）
4. 图片文字内容的相关性分析（如果有）
"""
        ai_response = await deepseek_client.send_message(prompt)
        ai_result = ai_response['choices'][0]['message']['content']
        
        # 生成Word文档
        doc_generator = DocGenerator()
        doc_path = os.path.join("temp", "docs")
        filename = doc_generator.generate_doc(
            original_text=combined_text,
            ai_analysis=ai_result,
            output_path=doc_path
        )
        
        return JSONResponse(content={
            "success": True,
            "original_text": combined_text,
            "ai_result": ai_result,
            "filename": filename
        })
        
    except Exception as e:
        logger.error(f"PDF处理错误: {str(e)}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={"success": False, "error": str(e)})


@router.post("/api/chat-stream")
async def chat_stream(file: UploadFile = File(...), prompt: str = Form(...)):
    try:
        # 读取图片文件
        image_content = await file.read()
        image_base64 = base64.b64encode(image_content).decode('utf-8')


        # 获取流式生成器
        stream_generator = deepseekImg_client.chat_with_image_stream(
            image_base64=image_base64,
            prompt=prompt
        )

        # 返回流式响应
        return await deepseekImg_client.process_stream_response(stream_generator)

    except Exception as e:
        logger.error(f"流式对话请求失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))